package com.example.tutorial.java.concurrent.practice.ch3;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 要安全的发布一个对象，对象的引用以及对象的状态必须同时对其它线程可见，有以下几种方式
 *
 * @author: cph
 * @date: 2022-4-17
 */
public class SafePublishObject {

    /**
     * 在静态初始化函数中初始化一个对象引用
     */
    public static SafePublishObject s = new SafePublishObject();

    /**
     * 将对象的引用保存到volatile类型的域或AtomicReference对象中
     */
    public volatile SafePublishObject v = new SafePublishObject();
    public AtomicReference<SafePublishObject> a = new AtomicReference<>();

    /**
     * 将对象的引用保存到某个正确构造对象的final域中？
     */
    private final Set<String> stooges = new HashSet<>();

    public SafePublishObject() {
        stooges.add("ttt");
        stooges.add("sss");
    }

    public boolean isStooge(String str) {
        return stooges.contains(str);
    }

    /**
     * 将对象的引用保存到一个由锁保护的域中
     */
    private ConcurrentHashMap map = new ConcurrentHashMap();
    private ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue();


}
